package cn.wolfcode.wolf2w.service.impl;

import cn.wolfcode.wolf2w.domain.Region;
import cn.wolfcode.wolf2w.query.RegionQuery;
import cn.wolfcode.wolf2w.repository.RegionRepsitory;
import cn.wolfcode.wolf2w.service.IRegionService;
import cn.wolfcode.wolf2w.util.DBHelper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.*;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.mongodb.core.query.Update;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.List;

@Service
//@Transactional  现在写不能事务, 需要讲完复制集才能使用事务
public class RegionServiceImpl implements IRegionService {

    @Autowired
    private RegionRepsitory repsitory;

    @Autowired
    private MongoTemplate template;



    @Override
    public void save(Region region) {
        region.setId(null);
        repsitory.save(region);
    }

    @Override
    public void update(Region region) {
        repsitory.save(region);
    }

    @Override
    public void delete(String id) {
        repsitory.deleteById(id);
    }

    @Override
    public Region get(String id) {
        return repsitory.findById(id).orElse(null);
    }

    @Override
    public List<Region> list() {
        return repsitory.findAll();
    }

    @Override
    public Page<Region> query(RegionQuery qo) {
        Query query = new Query();
        Pageable pageable = PageRequest.of(qo.getCurrentPage()- 1,qo.getPageSize(), Sort.Direction.ASC, "_id");
        return DBHelper.query(template,pageable, query,Region.class, qo);
    }

    @Override
    public void saveOrUpdate(Region region) {
        if(StringUtils.hasLength(region.getId())){
            //update
            //mongodb - repsitory 的更新操作时全量更新
            //为啥此处操作没有出现参数丢失问题呢?
            //region编辑时页面修改数据个数刚好跟表中列个数一致
            //即: 是全量修改
            this.update(region);
        }else{
            //save
            this.save(region);
        }
    }

    @Override
    public void changeHotValue(String id, int hot) {

        //全量更新操作
        //查询
        //Region region = this.get(id);
        //替换
        //region.setIshot(hot);
        //更新
        //this.update(region);

        //---------------------
        //部分字段更新
        //db.集合.updateMany({_id:id}, {$set:{ishot:hot}})
        Query query = new Query();
        query.addCriteria(Criteria.where("_id").is(id));
        Update update = new Update();
        update.set("ishot", hot);
        template.updateMulti(query, update, Region.class);

    }

    @Override
    public List<Region> queryHotRegion() {

        //1:必须热门
        //2:排序
        return repsitory.findByIshotOrderBySequence(Region.STATE_HOT);
    }
}
